package Socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;

    public Client(){

        try {
            System.out.println("正在连接服务器...");
            socket=new Socket("176.201.104.11",8088);
            System.out.println("连接成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void start(){
        OutputStream os= null;
        try {
            os = socket.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw=new BufferedWriter(osw);
            PrintWriter pw=new PrintWriter(bw,true);

            Scanner scan = new Scanner(System.in);
            while (true) {
                System.out.println("请输入昵称");
                String nickname = scan.nextLine();
                if (nickname.trim().isEmpty()){
                    System.out.println("昵称不能为空");
                }else {
                    pw.println(nickname);
                    System.out.println("欢迎您:"+nickname+",请开始聊天吧");
                    break;
                }
            }

            ServerHandler handler=new ServerHandler();
            Thread t=new Thread(handler);
            t.setDaemon(true);
            t.start();

            while (true){
                System.out.println("请输入内容");
                String scan1 = scan.next();
                if ("exit".equalsIgnoreCase(scan1)){
                    break;

                }else {
                    pw.println(scan1);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client=new Client();
        client.start();
    }
    private class ServerHandler implements Runnable{
        public void run(){
                try {
                    InputStream is=socket.getInputStream();
                    InputStreamReader isr=new InputStreamReader(is, StandardCharsets.UTF_8);
                    BufferedReader br=new BufferedReader(isr);

                    String message;
                    while ((message=br.readLine())!=null){
                        System.out.println(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}